﻿using System.Runtime.CompilerServices;

namespace RainbowNavBar
{
    public partial class MainWindow : Window
    {
        private delegate void LabelMouseDownHandler(Entries ed, Label label);
        private event LabelMouseDownHandler LabelAddMouseDown;

        private delegate void LableReloadData(TagData obj);
        private static event LableReloadData LReloadData;

        private delegate int LRPointW();
        private static event LRPointW PointL;
        private static event LRPointW PointR;

        private System.Windows.Forms.NotifyIcon notifyIcon;
        private System.Windows.Forms.ContextMenuStrip contextMenu;

        private static Label MyComputer = null;

        public MainWindow()
        {
            InitializeComponent();

            // 事件：数据监控
            ApplicationConfig.ItemAdded += List_ItemAdded;
            ApplicationConfig.ItemUpdated += List_ItemUpdated;
            ApplicationConfig.ItemRemoved += List_ItemRemoved;

            // 标签：点击事件
            this.LabelAddMouseDown += MainWindow_LabelAddMouseDown;

            // 加载：窗体加载
            this.Loaded += (s, e) =>
            {
                ApplicationConfig.CreateConfig(ApplicationConfig.ConfigPath);

                //Debug.WriteLine(ApplicationConfig.ConfigPath);

                //Debug.WriteLine(ApplicationConfig.configManager.GetAppConfigValue("Location"));
                //Debug.WriteLine(ApplicationConfig.configManager.GetAppConfigValue("StartUp"));
                //Debug.WriteLine(ApplicationConfig.configManager.GetAppConfigValue("Computer"));

                // 读取应用配置
                AppConfig.StartUp = Convert.ToBoolean(ApplicationConfig.configManager.GetAppConfigValue("StartUp"));
                AppConfig.Location = Convert.ToBoolean(ApplicationConfig.configManager.GetAppConfigValue("Location"));
                AppConfig.Computer = Convert.ToBoolean(ApplicationConfig.configManager.GetAppConfigValue("Computer"));

                this.Width = 150;

                // 设置导航位置
                this.SetPointWindw(AppConfig.Location);

                // 设置固定标签(我的电脑)
                OpenComputerTag();

                // 获取数据，将标签添加到窗口中
                LoadData();

                InitializeTrayIcon();

                // 窗口移除Alt+Tab视图
                HideView.HideAltTab(this);

                // 调试
                //Debug.WriteLine(ApplicationConfig.configManager.GetAppConfigValue("Language"));

            };

            // 加载：排序后重新加载标签数据
            LReloadData += (s) =>
            {
                MainWindowStackPanel.Children.Clear();
                // 装载数据
                //ApplicationConfig.GetTagData();

                //AddTextBlockToStackPanel(Color.FromRgb(33, 150, 243), "我的电脑", "explorer", 1);

                // 标签：我的电脑
                MainWindowStackPanel.Children.Add(MyComputer);

                foreach (TagData item in ApplicationConfig.TagListData)
                {

                    //AddTextBlockToStackPanel(item.TagLabel, item.TagAddress, (int)item.TagType);
                    // 判断是否启用
                    MainWindowStackPanel.Children.Add(item.TagLabel);

                    //LabelAddMouseDown?.Invoke(new Entries() { FunType = (FunType)item.TagType, Address = item.TagAddress }, item.TagLabel);

                    if (!item.TagEnable)
                    {
                        item.TagLabel.Visibility = Visibility.Collapsed;
                    }
                }

            };

            #region 位置回调

            PointL += () =>
            {
                SetPointWindw(true);
                return 0; 
            };
            PointR += () =>
            {
                SetPointWindw(false);
                return 0;
            };

            #endregion
        }

        #region 导航：设置位置

        /// <summary>
        ///  设置导航位置
        /// </summary>
        /// <param name="T">true:右侧 false:左侧</param>
        private void SetPointWindw(bool T = true)
        {
            if (T)
            {
                this.Left = 0;
                this.Top = SystemParameters.PrimaryScreenHeight / 2 - this.Height / 2 - 100;
                this.MainWindowStackPanel.HorizontalAlignment = HorizontalAlignment.Left;
            }
            else
            {
                this.Left = SystemParameters.PrimaryScreenWidth - this.Width;
                this.Top = SystemParameters.PrimaryScreenHeight / 2 - this.Height / 2 - 100;
                this.MainWindowStackPanel.HorizontalAlignment = HorizontalAlignment.Right;
            }
        }

        /// <summary>
        /// 将标签导航设置到屏幕左侧
        /// </summary>
        public static void SetPointWLeft()
        {
            // 设置“我的电脑”标签
            MyComputer.HorizontalAlignment = HorizontalAlignment.Left;
            MyComputer.HorizontalContentAlignment = HorizontalAlignment.Right;

            ApplicationConfig.configManager.SetAppConfigValue("Location", "True");
            PointL.Invoke();
        }

        /// <summary>
        /// 将标签导航设置到屏幕右侧
        /// </summary>
        public static void SetPointWRight()
        {
            // 设置“我的电脑”标签
            MyComputer.HorizontalAlignment = HorizontalAlignment.Right;
            MyComputer.HorizontalContentAlignment = HorizontalAlignment.Left;

            ApplicationConfig.configManager.SetAppConfigValue("Location", "False");
            PointR.Invoke();
        }

        #endregion

        #region 回调：标签操作

        /// <summary>
        /// 回调：删除标签
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void List_ItemRemoved(TagData obj)
        {
            Debug.WriteLine("删除数据！");

            MainWindowStackPanel.Children.Remove(obj.TagLabel);
        }

        /// <summary>
        /// 回调：更新标签
        /// </summary>
        /// <param name="arg1"></param>
        /// <param name="arg2"></param>
        /// <param name="arg3"></param>
        private void List_ItemUpdated(TagData td, string tn, Dictionary<string, string> dic)
        {
            if (!Convert.ToBoolean(dic["TagEnable"]))
            {
                td.TagLabel.Visibility = Visibility.Collapsed;
                return;
            }
            else
            {
                td.TagLabel.Visibility = Visibility.Visible;
            }

            try
            {
                td.TagLabel.Content = dic["TagName"];
                td.TagLabel.Background = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(dic["TagColor"]));
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{ex.Message}");

                td.TagLabel.Content = td.TagName;
                td.TagLabel.Background = new SolidColorBrush(td.TagColor);
            }
            finally
            {
                if (!td.IsModify)
                {
                    LabelAddMouseDown?.Invoke(new Entries() { FunType = (FunType)td.TagType, Address = td.TagAddress }, td.TagLabel);
                }
            }
        }

        /// <summary>
        /// 回调：添加标签
        /// </summary>
        /// <param name="obj"></param>
        private void List_ItemAdded(TagData obj)
        {
            if (!Convert.ToBoolean(obj.TagEnable))
            {
                obj.TagLabel.Visibility = Visibility.Collapsed;
            }
            else
            {
                obj.TagLabel.Visibility = Visibility.Visible;
            }
            try
            {
                obj.TagLabel.Content = obj.TagName;
                obj.TagLabel.Background = new SolidColorBrush(obj.TagColor);
            }
            catch
            {

            }
            finally
            {
                // 添加标签到UI中
                MainWindowStackPanel.Children.Add(obj.TagLabel);
                LabelAddMouseDown?.Invoke(new Entries() { FunType = (FunType)obj.TagType, Address = obj.TagAddress }, obj.TagLabel);
            }
        }

        #endregion

        #region 窗体：数据配置

        /// <summary>
        /// 重新加载窗口标签标签
        /// </summary>
        public static void ReloadData()
        {
            LReloadData.Invoke(null);
        }

        /// <summary>
        /// 加载窗口标签数据
        /// </summary>
        private void LoadData()
        {
            // 状态：我的电脑
            IsOpenComputer(AppConfig.Computer);

            // 标签：我的电脑
            MainWindowStackPanel.Children.Add(MyComputer);

            // 装载数据
            ApplicationConfig.GetTagData();

            //AddTextBlockToStackPanel(Color.FromRgb(33, 150, 243), "我的电脑", "explorer", 1);

            foreach (var item in ApplicationConfig.TagListData)
            {
                if (AppConfig.Location)
                {
                    item.TagLabel.HorizontalAlignment = HorizontalAlignment.Left;

                    item.TagLabel.HorizontalContentAlignment = HorizontalAlignment.Right;
                }
                else
                {
                    item.TagLabel.HorizontalAlignment = HorizontalAlignment.Right;
                    item.TagLabel.HorizontalContentAlignment = HorizontalAlignment.Left;
                }

                //AddTextBlockToStackPanel(item.TagLabel, item.TagAddress, (int)item.TagType);
                // 判断是否启用
                if (!item.TagEnable)
                {
                    item.TagLabel.Visibility = Visibility.Collapsed;
                }
            }

            //AddTextBlockToStackPanel(Color.FromRgb(33, 150, 243), "Google Translate", "https://translate.google.com/", 0);
            //AddTextBlockToStackPanel(Color.FromRgb(76, 175, 80), "TIM", @"D:\Program Files (x86)\Tencent\TIM\Bin\QQScLauncher.exe", 1);
            //AddTextBlockToStackPanel(Color.FromRgb(251, 192, 45), _type: 1);
            //AddTextBlockToStackPanel(Color.FromRgb(255, 69, 0), _type: 1);
            //AddTextBlockToStackPanel(Color.FromRgb(25, 118, 210), _type: 1);
            //AddTextBlockToStackPanel(Color.FromRgb(142, 36, 170), _type: 1);
            //AddTextBlockToStackPanel(Color.FromRgb(233, 66, 66), "退出应用", _type: 2);
            //AddTextBlockToStackPanel(Color.FromRgb(233, 66, 66), "应用设置", _type: 3);
        }

        /// <summary>
        /// 使用 NotifyIcon 创建托盘图标和菜单
        /// </summary>
        private void InitializeTrayIcon()
        {
            // 创建托盘图标
            //notifyIcon = new System.Windows.Forms.NotifyIcon
            //{
            //    Icon = new System.Drawing.Icon("pack://application:,,,Quick.ico"),  // 你需要一个 ICO 格式的图标文件
            //    Visible = true,
            //    Text = "彩虹导航",
            //};

            // 读取嵌入资源
            using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RainbowNavBar.icon.ico"))
            {
                notifyIcon = new System.Windows.Forms.NotifyIcon
                {
                    Icon = new System.Drawing.Icon(resourceStream),
                    Visible = true,
                    Text = "彩虹导航",
                };
            }

            // 鼠标左键单机
            notifyIcon.MouseClick += (s, e) =>
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Left) // 判断是否是鼠标左键点击
                {
                    if (ApplicationTagList == null)
                    {
                        ApplicationTagList = new TagManagement();
                        ApplicationTagList.Show();
                    }
                }
            };

            // 创建托盘菜单
            contextMenu = new System.Windows.Forms.ContextMenuStrip();
            var exitMenuItem = new System.Windows.Forms.ToolStripMenuItem("退出", null, (s, e) => { Application.Current.Shutdown(); });
            var NavMenuItem = new System.Windows.Forms.ToolStripMenuItem("偏好设置", null, (s, e) =>
            {
                if (ApplicationSettings == null)
                {
                    ApplicationSettings = new SettingView();
                    ApplicationSettings.Show(); ;
                }
            });

            var TagManagement = new System.Windows.Forms.ToolStripMenuItem("标签管理", null, (s, e) =>
            {
                if (ApplicationTagList == null)
                {
                    ApplicationTagList = new TagManagement();
                    ApplicationTagList.Show();
                }
            });

            // 添加分隔符
            var separator = new System.Windows.Forms.ToolStripSeparator();

            // 添加菜单项
            contextMenu.Items.Add(TagManagement);
            contextMenu.Items.Add(separator);
            contextMenu.Items.Add(NavMenuItem);
            contextMenu.Items.Add(exitMenuItem);

            // 绑定右键点击事件
            notifyIcon.ContextMenuStrip = contextMenu;
        }

        /// <summary>
        /// 添加相应功能条目
        /// </summary>
        /// <param name="background"></param>
        /// <param name="text"></param>
        private void AddTextBlockToStackPanel(Label _label, string address = null, int _type = 0)
        {
            //LabelAddMouseDown?.Invoke(new Entries() { FunType = (FunType)_type, Address = address }, _label);

            //MainWindowStackPanel.Children.Add(_label);

        }

        /// <summary>
        /// 添加相应的事件
        /// </summary>
        /// <param name="ftype"></param>
        /// <param name="label"></param>
        private void MainWindow_LabelAddMouseDown(Entries ed, Label label)
        {
            switch (ed.FunType)
            {
                case FunType.SETTINGS: { } break;
                case FunType.EXIT:
                    {
                        label.MouseDown += (s, e) =>
                        {
                            if (MessageBox.Show("确定要退出导航应用吗？", "退出提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                            {
                                Application.Current.Shutdown();
                            }
                        };
                    }
                    break;
                case FunType.URL:
                    {
                        label.MouseDown += (s, e) =>
                        {
                            Process.Start(ed.Address);
                        };
                    }
                    break;
                case FunType.APPLICATION:
                    {
                        label.MouseDown += (s, e) =>
                        {
                            Process.Start(ed.Address);
                        };
                    }
                    break;
                case FunType.FILE:
                    {
                        label.MouseDown += (s, e) =>
                        {
                            Process.Start(ed.Address);
                        };
                    }
                    break;
            }
        }

        /// <summary>
        /// 关闭时释放托盘图标
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            notifyIcon.Dispose();  // 释放托盘图标资源
            base.OnClosed(e);
        }

        #endregion

        #region 标签：固定标签

        // private readonly BitmapImage FolderIcon = new(new Uri());

        /// <summary>
        /// 创建“我的电脑”标签
        /// </summary>
        private void OpenComputerTag()
        {
            Label _label = new()
            {
                Width = 10,
                Height = 30,
                Content = "我的电脑",
                Background = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#1C99E3")),
            };
            _label.MouseDown += (s, e) =>
            {
                Process.Start("explorer.exe");
            };
            MyComputer = _label;
        }

        /// <summary>
        /// 设置是否开启“我的电脑”标签
        /// </summary>
        public static void IsOpenComputer(bool sc)
        {
            MyComputer.Visibility = sc ? Visibility.Visible : Visibility.Collapsed;
        }

        #endregion

    }
}
